<template>
    <div class="link_container">
        <ZWGroup ref="ZWGroupRef" :group-id="groupId" :type="6" @submit="init" />
        <div class="link_main">
            <div class="link_search">
                <ZwSearchForm row-num="3" :option="searchOption" @search="searchResult" @reset="reset" />
            </div>
            <div class="link_header_button">
                <FormulaBar
                    ref="FormulaBarRef"
                    :type="6"
                    :group-id="groupId"
                    @handleCheckAllChange="handleCheckAllChange"
                    @batchTag="batchTag"
                    @batchDel="batchDel"></FormulaBar>
            </div>
            <el-scrollbar v-if="tableData.length > 0" class="link_list">
                <div class="link_content">
                    <Details
                        ref="details"
                        class="img_details_item"
                        :table-data="tableData"
                        @isBatch="isBatch"></Details>
                </div>
            </el-scrollbar>
            <el-empty v-else image="/static/noData.png" description="暂无数据"></el-empty>
            <!-- 分页 -->
            <ZWPagination ref="PaginationRef" @submit="getPage" />
        </div>
        <!-- 删除弹框 -->
        <ZWDeletdialog ref="DeletdialogRef" @submit="batchRemove" />
        <!-- 上传弹框 -->
        <Upload ref="UploadRef" :type="6" :group-id="groupId === 'all' ? 0 : groupId" @submit="onSubmitUpload" />
    </div>
</template>

<script setup lang="ts">
import ZWGroup from '@/components/ZWGroup.vue';
import Search from '../../components/Search.vue';
import FormulaBar from './components/FormulaBar.vue';
import Upload from './components/Upload.vue';
import Details from './components/Details.vue';
import ZWDeletdialog from '@/components/ZWDeletdialog.vue';
import ZWPagination from '@/components/ZWPagination.vue';
import { ref, reactive, onMounted, watch, computed } from 'vue';
import { linkList, batchContentDel } from '@/api/concreation';
import ZwSearchForm from '@/components/zw/search-form/SearchForm';
import { useStore } from '@/store';
import { batchTagAdd, batchTagDel, getCreateList } from '@/api/common';
import { getSetionId, treeH, reSize } from '@/utils/utils';
import { deepCopy } from '@/utils/helper';
import { ElMessage } from 'element-plus';
import router from '@/router';
import bus from '@/utils/bus';
import { useRoute } from 'vue-router';
import { endLoading, startLoading } from '@/utils/request';
const route = useRoute();
const groupId = ref<number | string>('all');
const ZWgroupId = ref(0);
const ZWGroupRef: any = ref(null);
const UploadRef = ref();
const DeletdialogRef = ref(null);
const details = ref(null);
// 选择IDList
const sectionIds = ref([]);
// 选中的id
const selfSelectId = ref([]);
const scrollbarHeight = ref<string>('400px');

// 分组
const group = computed(() => {
    return store.getters['content/group'];
});
let params = reactive({
    page_size: 15,
    page: 1,
    group_id: groupId.value || 0,
    title: '',
    user_id: '',
    created_time: [],
    is_radar: '',
    tag_list: ''
});
const searchOption = computed(() => {
    return [
        {
            label: '链接搜索',
            name: 'title',
            value: '',
            type: 'input',
            width: '280px',
            placeholder: '请输入标题进行查询'
        },
        {
            label: '创建者',
            name: 'user_id',
            value: [],
            multiple: true,
            type: 'select',
            filterable: true,
            placeholder: '全部',
            fetchOptionApi: () => {
                return new Promise(resolve => {
                    getCreateList({}).then((res: any) => {
                        const targetArr = res.map((item: any) => {
                            item.name = `${item.name}  (${item.phone})`;
                            return item;
                        });
                        resolve(targetArr);
                    });
                });
            },
            formatOption: (v: any) => ({
                label: v.name,
                value: v.id
            })
        },
        {
            label: '创建时间',
            name: 'created_time',
            value: [],
            type: 'datePicker',
            datePickerType: 'daterange',
            datePickerFormat: 'YYYY-MM-DD HH:mm:ss',
            valueFormat: 'YYYY-MM-DD HH:mm:ss',
            startPlaceholder: '开始时间',
            endPlaceholder: '结束时间'
        },
        {
            label: '标签筛选',
            name: 'tag_list',
            value: [],
            type: 'select',
            placeholder: '请选择标签',
            multiple: true,
            popperClass: 'zw-hide_select_option',
            isTagSelect: true,
            formatOption: v => ({
                label: v.name,
                value: v.id
            })
        }
    ];
});
const defaultParams = reactive({
    title: '',
    user_id: [],
    created_time: [],
    is_radar: -1,
    tag_list: [],
    group_id: groupId.value || 0
});
const state = reactive({
    searchParams: deepCopy(defaultParams)
});
const reset = (v?: any) => {
    params = { ...params, ...defaultParams };
    getLinkListes();
    details.value?.clearSelection();
};
const groupSearch = (data: any) => {
    params.group_id = data.id;
    getLinkListes();
};
const handleCheckAllChange = (val: boolean) => {
    details.value?.change(val);
};
// 是否是批量删除
const isBatch = (data: any) => {
    IsBatch.value = false;
    DeletdialogRef.value.appDialog.visible = true;
    selfSelectId.value = [data as never];
};
// 批量删除
const batchDel = () => {
    IsBatch.value = true;
    DeletdialogRef.value.appDialog.visible = true;
};
//是否批量
const IsBatch = ref(true);
// 批量确认
const batchTag = async (data: any) => {
    const paramsData = {
        type: 1,
        content_ids: sectionIds.value,
        tag_ids: getSetionId('id', data.tag_ids) //选中标签ID
    };
    startLoading();
    //0 批量打 1批量删除      //批量打标签              // 批量删除
    try {
        data.defaultVal == 0 ? await batchTagAdd(paramsData, true) : await batchTagDel(paramsData, true);
        ElMessage.success(`批量${data.defaultVal ? '移除' : '打'}标签成功`);
        getLinkListes();
        details.value?.clearSelection();
    } catch (e) {
        // console.log(e, '--');
        endLoading();
    }
};
// 删除确认
const batchRemove = async () => {
    startLoading();
    try {
        //  删除
        await batchContentDel({
            type: 6,
            content_ids: IsBatch.value ? sectionIds.value : selfSelectId.value
        });
        ElMessage.success(`${IsBatch.value ? '批量' : ''}删除成功`);
        DeletdialogRef.value.appDialog.visible = false;
        details.value?.clearSelection();
        store.dispatch('table', {
            tableData: [],
            tableAll: false
        });
        refreshGroup();
    } catch (e) {
        endLoading();
    }
};
bus.on('batchTag', batchTag);
// 全选部分
const change = (data: any) => {
    sectionIds.value = data;
};
bus.on('change', change);
const store = useStore();
const pageInfo = reactive({
    page_size: 15,
    page: 1
});
const tableData = ref([]);
// 搜索
const searchResult = (data?: any) => {
    params.page_size = pageInfo.page_size;
    params.page = pageInfo.page;
    params.title = data?.title || '';
    params.user_id = data?.user_id || '';
    params.created_time = data?.created_time || '';
    // params.is_radar = data?.type || ''
    params.tag_list = data?.tag_list || '';
    getLinkListes();
    details.value?.clearSelection();
};
//获取列表
const getLinkListes = async () => {
    startLoading();
    try {
        const data = await linkList(params, true);
        data.data.map((item: any) => {
            item.compilesss = [
                {
                    isShow: false,
                    name: 'statistics',
                    content: '详情'
                },
                {
                    isShow: false,
                    name: 'delete',
                    content: '删除'
                },
                {
                    isShow: false,
                    name: 'download',
                    content: '下载'
                },
                {
                    isShow: false,
                    name: 'write',
                    content: '编辑'
                },
                {
                    isShow: false,
                    name: 'copy',
                    content: '分享'
                }
            ];
        });
        // ZWgroupId.value=0
        tableData.value = data.data;
        store.dispatch('pageTotal', data.total);
    } catch (error) {
    } finally {
        endLoading();
    }
};
//分页
const getPage = (val: any) => {
    (pageInfo.page_size = val.page_size), (pageInfo.page = val.page), searchResult();
};
const init = (val?: any) => {
    if (val) {
        defaultParams.group_id = val?.id || 0;
        groupId.value = val?.id || 0;
    } else {
        defaultParams.group_id = groupId.value;
    }
    params.group_id = groupId.value;

    params.page_size = 15;
    params.page = 1;
    // params.group_id = val?.id || 0;
    // groupId.value = val?.id;
    // UploadRef.value.form.group_id = val?.id || 0
    getLinkListes();
    details.value?.clearSelection();
};
const refreshGroup = () => {
    ZWGroupRef.value.getGroup();
    getLinkListes();
};
// 快速创建/编辑弹框保存
const onSubmitUpload = (data: any) => {
    if (data) {
        groupId.value = data.id;
        defaultParams.group_id = data.id;
        params.group_id = data.id;
        ZWGroupRef.value.getGroup();
        ZWGroupRef.value.changeGroup({ id: data.id });
        getLinkListes();
    } else {
        refreshGroup();
        details.value?.clearSelection();
    }
};

/**
 * @description: 获取内容区域滚动高度
 * @return {*}
 */
const getScrollbarHeight = () => {
    const h = treeH('.img_details', 140);
    scrollbarHeight.value = `${h}px`;
};

onMounted(async () => {
    init();

    getScrollbarHeight();
    reSize(() => getScrollbarHeight());
});
</script>

<style lang="scss" src="./style.scss" scoped></style>
